import React, { Component } from 'react';
import { Table, DatePicker, Row } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const colunms = [
	{
		title: '搜索时间',
		dataIndex: 'time',
		key: 'time',
		render(text, recard) {
			if (recard.dateFlag) {
				return <strong>{text}</strong>;
			} else {
				return <span>{text}</span>;
			}
		}
	},
	{
		title: '搜索内容',
		dataIndex: 'content',
		key: 'content'
	}
];

const dataSource = [
	{
		key: '1',
		time: '2018-08-06 11:27:00',
		content: '本发明公开了一种无人农药喷洒装置.包括集体.固定在机体底部左右两侧的支撑架以..'
	},
	{
		key: '2',
		time: '2018-08-06 11:27:00',
		content: '本发明公开了一种无人农药喷洒装置.包括集体.固定在机体底部左右两侧的支撑架以..'
	}
];
// 根据日期分组
const format = (data) => {
	let res = [];
	let flag;
	const sortedSource = _.sortBy(data, (o) => {
		return -moment(o.time);
	});
	sortedSource.forEach((item) => {
		const obj = moment(item.time);
		if (flag !== item.time) {
			flag = item.time;

			res.push({
				key: item.key.toString() + '-flag',
				time: `${obj.fromNow()} - ${obj.format('YYYY 年 M 月 D 日 - dddd')}`,
				dateFlag: true
			});
		}
		res.push({
			...item,
			time: obj.format('a h:mm:ss')
		});
	});
	return res;
};

export default class SearchTable extends Component {
	constructor(props) {
		super(props);
		this.state = {
			formatDateSource: [],
			loading: 0
		};
	}
	onChange(dates) {
		this.setState({
			loading: this.state.loading + 1
		});
		if (dates.length) {
			const filterSource = dataSource.filter((item) => moment(item.time).isBetween(dates[0], dates[1], 'day', '[]'));
			this.setState({
				formatDateSource: format(filterSource)
			});
		} else {
			this.setState({
				formatDateSource: format(dataSource)
			});
		}
		this.setState({
			loading: this.state.loading - 1
		});
	}
	componentDidMount() {
		this.setState({
			formatDateSource: format(dataSource)
		});
	}
	render() {
		return (
			<div>
				<Row type="flex" justify="end" align="middle">
					<DatePicker.RangePicker style={{ marginBottom: '.5em' }} onChange={this.onChange.bind(this)} />
				</Row>
				<div style={{ overflowX: 'scroll' }}>
					<Table
						pagination={false}
						dataSource={this.state.formatDateSource}
						columns={colunms}
						style={{ backgroundColor: '#fff', minWidth: '800px' }}
						loading={this.state.loading > 0}
					/>
				</div>
			</div>
		);
	}
}
